//
//  CityPickerView.swift
//  城市选择器
//
//  Created by 千策万划-mini on 2025/5/6.
//

import Foundation

class CityPickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate {
    
    var blockConfirmClick: ((String) -> Void)?
    var modelDetail: ModelCity = ModelCity()
    var selectValue: String = ""
    var titleStr: String = ""
    var subTitleStr: String = ""
    var selectedProvinceIndex = 0
    var selectedCityIndex = 0
    var selectedDistrictIndex = 0
    
    // MARK: - lazy
    lazy var imageBack: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(355), W(508))
        result.image = UIImage(named: "icon_idcard_example_bg")
        return result
    }()
    lazy var btnClose: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(40 + 16 * 2, 40 + 30 * 2)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()
    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()
    lazy var labelSubTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()
    lazy var imageContent: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(275), W(290))
        result.image = UIImage(named: "icon_login_input_bg")
        return result
    }()
    lazy var btnConfirm: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(168), W(46))
        result.setBackgroundImage(UIImage(named: "icon_pop_cancel"), for: .normal)
        result.tag = 2
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        let label = OutlineLabel()
        label.resetView(
            title: "Confirming",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 16),
            shadowColor: UIColor(hex: "#1B4506"),
            outlineColor: UIColor(hex: "#004600")
        )
        label.centerXCenterY = XY(result.width / 2, result.height / 2)
        result.addSubview(label)
        return result
    }()
    lazy var pickerView: UIPickerView = {
        let result = UIPickerView()
        result.dataSource = self
        result.delegate = self
        return result
    }()
    lazy var imagePickerIndicator: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = false
        result.image = UIImage(named: "icon_login_tf_bg")
        return result
    }()
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT)
        backgroundColor = UIColor(hex: "000000", alpha: 0.8)
       
        let jsonString = GlobalMethod.readStrFromUserDefaults(forKey: LOCAL_CITY_LIST)
        let dicItem = GlobalMethod.exchangeStringToDic(jsonString)
        modelDetail = ModelCity.deserialize(from: dicItem) ?? ModelCity()
        
        addSubView()
        // 刷新PickerView
        pickerView.reloadAllComponents()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        for subview in pickerView.subviews {
            subview.backgroundColor = .clear
        }
    }
    
    // MARK: - 添加
    func addSubView() {
        addSubview(imageBack)
        imageBack.addSubview(labelTitle)
        imageBack.addSubview(labelSubTitle)
        imageBack.addSubview(imageContent)
        imageBack.addSubview(btnClose)
        imageBack.addSubview(btnConfirm)
        imageContent.addSubview(imagePickerIndicator)
        imageContent.addSubview(pickerView)
        resetView()
    }
    
    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            hide()
        case 2:
            let modelPro  = modelDetail.teasing[selectedProvinceIndex]
            let modelCity = modelPro.teasing[selectedCityIndex]
            let modelDist = modelCity.teasing[selectedDistrictIndex]
            selectValue = "\(modelPro.cautiously)-\(modelCity.cautiously)-\(modelDist.cautiously)"
            if let block = blockConfirmClick {
                block(self.selectValue)
            }
            hide()
        default:
            break
        }
    }

    // 显示
    func show() {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            // 设置初始状态（比如从底部开始）
            alpha = 0
            imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
            window.addSubview(self)
            // 添加弹出动画
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
                self.alpha = 1
                self.imageBack.transform = .identity
            }
        }
    }

    // 隐藏
    func hide() {
        // 添加消失动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.alpha = 0
            self.imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
        } completion: { _ in
            self.removeFromSuperview()
            // 重置 transform，以便下次显示
            self.imageBack.transform = .identity
        }
    }
    
    // MARK: - UIPickerView
    func numberOfComponents(in _: UIPickerView) -> Int {
        return 3;
    }

    func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 2:
            let modelPro  = modelDetail.teasing[selectedProvinceIndex]
            let modelCity = modelPro.teasing[selectedCityIndex]
            return modelCity.teasing.count
        case 1:
            let modelPro = modelDetail.teasing[selectedProvinceIndex]
            return modelPro.teasing.count
        case 0:
            return modelDetail.teasing.count
        default:
            return 0
        }
    }

    func pickerView(_: UIPickerView, rowHeightForComponent _: Int) -> CGFloat {
        return 60
    }

    func pickerView(_: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let customLabel = (view as? UILabel) ?? {
            let label = UILabel()
            label.textAlignment = .center
            label.font = UIFont.customBoldFont(size: 16)
            label.textColor = UIColor(hex: "#5228D7")
            return label
        }()
        let title: String
        switch component {
        case 0:
            let modelPro = modelDetail.teasing[row]
            title = modelPro.cautiously
        case 1:
            let modelPro = modelDetail.teasing[selectedProvinceIndex]
            let modelCity = modelPro.teasing[row]
            title = modelCity.cautiously
        case 2:
            let modelPro = modelDetail.teasing[selectedProvinceIndex]
            let modelCity = modelPro.teasing[selectedCityIndex]
            let modelDist = modelCity.teasing[row]
            title = modelDist.cautiously
        default:
            title = ""
        }
        customLabel.text = title
        customLabel.textColor = UIColor(hex: "#5228D7")
        return customLabel
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch component {
        case 0:
            // 更新省份索引
            self.selectedProvinceIndex = row
            // 重置城市和区县索引
            self.selectedCityIndex = 0
            self.selectedDistrictIndex = 0
            // 更新其他列的选择
            updateOtherColumns(pickerView, forProvince: row)
        case 1:
            // 更新城市索引
            self.selectedCityIndex = row
            // 重置区县索引
            self.selectedDistrictIndex = 0
            // 更新区县列的选择
            pickerView.selectRow(0, inComponent: 2, animated: true)
        case 2:
            // 更新区县索引
            self.selectedDistrictIndex = row
        default:
            break
        }
        pickerView.reloadAllComponents()
    }
    
    // 辅助方法：更新其他列的选择
    private func updateOtherColumns(_ pickerView: UIPickerView, forProvince provinceIndex: Int) {
        // 更新城市列
        pickerView.selectRow(0, inComponent: 1, animated: true)
        // 更新区县列
        pickerView.selectRow(0, inComponent: 2, animated: true)
    }

    // MARK: - 重置界面
    func resetView() {
        imageBack.centerXCenterY = XY(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
        btnClose.rightTop = XY(imageBack.width, 0)
        
        labelSubTitle.isHidden = !isStr(subTitleStr)
        if isStr(titleStr) {
            labelTitle.resetView(
                title: titleStr,
                textColor: COLOR_WHITE(),
                font: UIFont.customBoldFont(size: 24),
                shadowColor: UIColor(hex: "#4105A0"),
                outlineColor: UIColor(hex: "#3B0B9A")
            )
        }
//        if isStr(subTitleStr){
            labelTitle.centerXTop = XY(imageBack.width / 2, W(26))
//        }else{
//            labelTitle.centerXTop = XY(imageBack.width/2, W(16))
//            labelSubTitle.centerXTop = XY(imageBack.width/2, labelTitle.bottom-W(17))
//        }
        
        imageContent.centerXTop = XY(imageBack.width / 2, W(126))

        pickerView.widthHeight = XY(imageContent.width-W(10)*2, imageContent.height-W(20)*2)
        pickerView.centerXCenterY = XY(imageContent.width / 2, imageContent.height/2)
        pickerView.backgroundColor = .clear
        for subview in pickerView.subviews {
            subview.backgroundColor = .clear
        }
        
        imagePickerIndicator.widthHeight = XY(imageContent.width - 10 * 2, 60)
        imagePickerIndicator.centerXCenterY = XY(imageContent.width / 2, imageContent.height / 2)

        btnConfirm.centerXTop = XY(imageBack.width / 2, imageContent.bottom + W(15))
    }
}
